package com.yogurt.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yogurt.edu.entity.Subject;
import com.yogurt.edu.entity.excel.SubjectData;
import com.yogurt.edu.service.SubjectService;
import com.yogurt.servicebase.handler.MyException;

/**
 * @Auther: 酸奶
 * @Date: 2020/07/09 16:05
 * @Description: EasyExcel监听器
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public SubjectService subjectService;

    public SubjectExcelListener() {}

    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //一行一行的读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {

        if (subjectData == null){
            throw new MyException(20001,"数据为空");
        }

        //判断是否存在一级分类
        Subject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        //说明不存在一级分类
        if (existOneSubject == null){
            //进行添加
            existOneSubject = new Subject();
            existOneSubject.setTitle(subjectData.getOneSubjectName()); //设置一级分类的名称
            existOneSubject.setParentId("0"); //设置一级分类的父id
            subjectService.save(existOneSubject);
        }

        String parentId = existOneSubject.getId();
        //判断是否存在二级分类
        Subject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), parentId);
        //说明不存在二级分类
        if (existTwoSubject == null){
            //进行添加
            existTwoSubject = new Subject();
            existTwoSubject.setTitle(subjectData.getTwoSubjectName()); //设置二级分类的名称
            existTwoSubject.setParentId(parentId); //设置二级分类的父id
            subjectService.save(existTwoSubject);
        }
    }


    //判断一级分类不能重复添加
    private Subject existOneSubject(SubjectService subjectService,String name){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        Subject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private Subject existTwoSubject(SubjectService subjectService,String name,String parentId){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",parentId);
        Subject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
